package view;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import java.util.Vector;

public class ResourceBundleWrapper {
	private ResourceBundle mainResourceBundle;
	private ResourceBundle currentResourceBundle;
	private HashMap<String, String> currentAdded;

	public ResourceBundleWrapper() {
		this.mainResourceBundle = ResourceBundle
				.getBundle("lang.MessagesBundle");
		this.currentResourceBundle = ResourceBundle.getBundle("lang.MessagesBundle", Locale.getDefault());
		this.currentAdded = new HashMap<String, String>();

	}

	public void refreshResourcesBundles() {
		this.currentResourceBundle = createUtf8PropertyResourceBundle(ResourceBundle.getBundle(
				"lang.MessagesBundle", Locale.getDefault()));
	}
	
	private static ResourceBundle createUtf8PropertyResourceBundle(ResourceBundle bundle) {
		  if (!(bundle instanceof PropertyResourceBundle)) return bundle;

		  return new Utf8PropertyResourceBundle((PropertyResourceBundle)bundle);
	}

	public String getString(String key) {
		String string;
		try {
			string = this.currentResourceBundle.getString(key);
			return string;
		} catch (MissingResourceException e) {
			try{
			string = this.mainResourceBundle.getString(key);
			}
			catch (MissingResourceException e1) {
				string = this.currentAdded.get(key);
			}
		}
		return string;
	}

	public void addKeyValue(String key, String value) {
		try {
			this.mainResourceBundle.getString(key);
			// si la cles n'est pas deja presente on l'ajoute
		} catch (Exception e) {
			//si elle est pa prise en compte quand mm
			if (!this.currentAdded.containsKey(key)) {
				try {
					// append in the bundle file
					FileWriter writer = new FileWriter(new File(
							"bin/lang/MessagesBundle.properties"), true);
					writer.append("\n" + key + " = " + value);
					writer.flush();
					writer.close();
					this.currentAdded.put(key, value);
					// Maj du mainResourceBundle
					this.mainResourceBundle = ResourceBundle
							.getBundle("lang.MessagesBundle");
				} catch (IOException e1) {
				}
			}
		}
	}

	public Vector<Locale> getAvailableLocale() {
		Vector<Locale> listAvailableLocale = new Vector<Locale>();
		File repLang = new File("bin/lang/");
		String[] fileList = repLang.list();
		for (String file : fileList) {
			StringTokenizer tokens = new StringTokenizer(file, "\\.|_");
			if (tokens.countTokens() == 4 || tokens.countTokens() == 5) {
				tokens.nextToken();
				String language = tokens.nextToken();
				String country = tokens.nextToken();
				Locale currentLocale = new Locale(language, country);
				listAvailableLocale.add(currentLocale);
			}
		}
		return listAvailableLocale;
	}
	
	private static class Utf8PropertyResourceBundle extends ResourceBundle {
		  PropertyResourceBundle bundle;

		  private Utf8PropertyResourceBundle(PropertyResourceBundle bundle) {
		    this.bundle = bundle;
		  }
		  /* (non-Javadoc)
		   * @see java.util.ResourceBundle#getKeys()
		   */
		  public Enumeration<String> getKeys() {
		    return bundle.getKeys();
		  }
		  /* (non-Javadoc)
		   * @see java.util.ResourceBundle#handleGetObject(java.lang.String)
		   */
		  protected Object handleGetObject(String key) {
		    String value = (String)bundle.handleGetObject(key);
		    try {
		    	if(value != null)
		      return new String (value.getBytes("ISO-8859-1"),"UTF-8") ;
		    	else
		    		throw new MissingResourceException(value, value, value);
		    } catch (UnsupportedEncodingException e) {
		      // Shouldn't fail - but should we still add logging message?
		      return null;
		    } 
		  }
	}

}
